# -*- coding: UTF-8 -*-
import md5
import os
import datetime

from pyramid.view import view_config
from pyramid.renderers import render_to_response
from pyramid.httpexceptions import HTTPFound
from sqlalchemy import and_, or_, desc

from pyramid.security import (
        remember,
        forget,
        IAuthenticationPolicy,
        )

from . import tz

from ..models.meta import (
    DBSession,
    )

from ..models.models import (
    Coupon,
    CouponRandom,
    User,
    Role
    )

from ..freedom.dateutil.parser import parse
from ..freedom.randomserial import get_random_serial
from ..freedom.paginator import Paginator


@view_config(route_name='coupons_page1')
@view_config(route_name='coupons_page2')
def coupons_page(request):
    id = request.matchdict.get('id')
    if id:
        exec('result = coupons_%s(request, %d)' % (request.matchdict.get('page') or 'index', int(id)))
    else:
        exec('result = coupons_%s(request)' % request.matchdict.get('page') or 'index')

    return result

@view_config(route_name='coupons_page3', permission='user_view')
@view_config(route_name='coupons_page4', permission='user_view')
def coupons_auth_page(request):
    id = request.matchdict.get('id')
    if id:
        exec('result = coupons_%s(request, %d)' % (request.matchdict.get('page') or 'index', int(id)))
    else:
        exec('result = coupons_%s(request)' % request.matchdict.get('page') or 'index')

    return result

def coupons_detail(request, id):
    coupon = DBSession.query(Coupon).get(id)
    return render_to_response('/front/coupons/detail.html', {'coupon': coupon}, request = request)

def coupons_list(request):
    now = datetime.datetime.now(tz)
    pagesize = 5

    coupon_q = DBSession.query(Coupon).filter(Coupon.startdate<now).filter(Coupon.status==3).filter(Coupon.enddate>now).order_by(desc(Coupon.startdate))
    paginator = Paginator(coupon_q, pagesize)
    paginator.page_from_url(request.url)

    tmpl_context = {'coupons':paginator}

    return render_to_response('/front/coupons/list.html', tmpl_context, request = request)

def coupons_get(request, id):
    #check the number
    coupon = DBSession.query(Coupon).get(id)
    if coupon.number - len(coupon.couponrandoms) <= 0:
        request.session.flash(u"十分抱歉，优惠券已经发放完毕!")
        return HTTPFound(location = request.referrer or request.route_url('index'))
    if DBSession.query(CouponRandom).filter(CouponRandom.couponid==id).filter(CouponRandom.userid==request.session["user_id"]).count() > 0:
        request.session.flash(u"十分抱歉，每位用户只能领取一张!")
        return HTTPFound(location = request.referrer or request.route_url('index'))

    #get the random coupon
    couponrandom = CouponRandom()
    #type 1, the 5ibang coupon, type2 the ad coupon
    if not coupon.coupontype in (1,2):
        couponrandom.randomserial = coupon.rule + get_random_serial(len(str(coupon.number))) 
    couponrandom.couponid = coupon.id
    couponrandom.userid = request.session["user_id"]

    DBSession.add(couponrandom)

    #turn to the user center
    return HTTPFound(request.route_url('user_page', page='index'))
